/*
 * ============================================================
 * router 路由
 */

const router = {
    setQueryConfig: function(param){ // 动态拼接参数到请求的url
        let _str = '?';
        for(var item in param){ 
            _str += item + "=" + param[item] + "&"; 
        }
        _str = _str.substring(0, _str.length-1); 
        return _str;
    },
    navigateBack: function(delta = 1){ // 关闭当前页面，返回上一页面或多级页面。
        uni.navigateBack({
            delta: delta
        });
    },
    navigateTo: function(url, param = null){ // 保留当前页面，跳转到应用内的某个页面
        if(param !== null){
            url += this.setQueryConfig(param);
        }
        uni.navigateTo({
            url: url
        });
    },
    redirectTo: function(url, param = null){ // 关闭当前页面，跳转到应用内的某个页面。
        if(param !== null){
            url += this.setQueryConfig(param);
        }
        uni.redirectTo({
            url: url
        });
    },
    reLaunch: function(url, param = null){ // 关闭所有页面，打开到应用内的某个页面。
        if(param !== null){
            url += this.setQueryConfig(param);
        }
        uni.reLaunch({
            url: url
        });
    },
    switchTab: function(url, param = null){ // 跳转到 tabBar 页面，并关闭其他所有非 tabBar 页面。
        if(param !== null){
            url += this.setQueryConfig(param);
        }
        uni.switchTab({
            url: url
        });
    },
}

/*
 * ============================================================
 * toast 数据缓存 信息、获取、存储、删除、清空
 */

const toast = {
    show: function(title, icon = 'none', mask = false, duration = 700){
        uni.showToast({
            title: title,
            icon: icon,
            mask: mask,
            duration: duration
        });
    },
    showImg: function(title, img = '/static/icon/cart.png', mask = true, duration = 700){
        uni.showToast({
            title: title,
            image: img,
            mask: mask,
            duration: duration
        });
    },
    success: function(title){
        uni.showToast({
            title: title
        });
    },
    loading: function(title = '加载中...', icon = 'loading', mask = true, duration = 700){
        this.show(title, icon, mask, duration);
    }
}


/*
 * ============================================================
 * localStorage 数据缓存 信息、获取、存储、删除、清空
 */

const localStorage = {
    getStore: function(key){ // 获取localStorage，同步接口
        if (!key) return;
        try {
            return uni.getStorageSync(key);
        } catch (e) {
            // error
            console.log('获取localStorage error:'+JSON.stringify(e));
        }
    },
    getStoreInfo: function(){
        // #ifdef H5 || MP-WEIXIN
        // 获取localStorage信息,同步接口
        try {
            return uni.getStorageInfoSync();
        } catch (e) {
            // error
            console.log('获取localStorage error:'+JSON.stringify(e));
        }
        // #endif
        // #ifdef APP-PLUS
        console.log("localStorage H5+App不支持")
        // #endif
    },
    setStore: function(key, obj){ // 存储localStorage，同步接口
        if (!key) return;
        if (typeof obj !== 'string') {
            obj = JSON.stringify(obj);
        }
        try {
            uni.setStorageSync(key, obj);
        } catch (e) {
            // error
            console.log('存储localStorage error:'+JSON.stringify(e));
        }
    },
    removeStore: function(key){ // 删除localStorage，同步接口
        if (!key) return;
        try {
            uni.removeStorageSync(key);
        } catch (e) {
            // error
            console.log('删除localStorage error:'+JSON.stringify(e));
        }
    },
    clearStore: function(){ // 清空localStorage，同步接口
        try {
            uni.clearStorageSync();
        } catch (e) {
            // error
            console.log('清空localStorage error:'+JSON.stringify(e));
        }
    }
}


/*
 * ============================================================
 * 手机校验
 */

function regPhone(phone){
	var reg=/^1[3456789]\d{9}$/;
	if(phone!=''&&reg.test(phone))
	{
		return true;
	}
	return false;
}

/*
 * ============================================================
 * 经纬度格式转换 E:119°32′形态
 */

function formatLocation(longitude, latitude) {
    if (typeof longitude === 'string' && typeof latitude === 'string') {
        longitude = parseFloat(longitude)
        latitude = parseFloat(latitude)
    }

    longitude = longitude.toFixed(2)
    latitude = latitude.toFixed(2)

    return {
        longitude: longitude.toString().split('.'),
        latitude: latitude.toString().split('.')
    }
}


/*
 * ============================================================
 * 时间格式转换
 * formatTime时间计时秒转00：00：00形态
 * dateUtils时间转换xx天前、xx小时前、刚刚
 */

function formatTime(time) {
    if (typeof time !== 'number' || time < 0) {
        return time
    }

    let hour = parseInt(time / 3600)
    time = time % 3600
    let minute = parseInt(time / 60)
    time = time % 60
    let second = time

    return ([hour, minute, second]).map(function (n) {
        n = n.toString()
        return n[1] ? n : '0' + n
    }).join(':')
}

const dateUtils = {
    UNITS: {
        '年': 31557600000,
        '月': 2629800000,
        '天': 86400000,
        '小时': 3600000,
        '分钟': 60000,
        '秒': 1000
    },
    humanize: function (milliseconds) { // 需优化：从秒开始对比
        let humanize = '';
        for (let key in this.UNITS) {
            if (milliseconds >= this.UNITS[key]) {
                humanize = Math.floor(milliseconds / this.UNITS[key]) + key + '前';
                break;
            }
        }
        return humanize || '刚刚';
    },
    parse: function (str) { //将"yyyy-mm-dd HH:MM:ss"格式的字符串，转化为一个Date对象
        let a = str.split(/[^0-9]/);
        return new Date(a[0], a[1] - 1, a[2], a[3], a[4], a[5]);
    },
    formatYear: function (dateStr) { //年以内转换、去除秒
        let date = this.parse(dateStr)
        let diff = Date.now() - date.getTime();
        return this.humanize(diff);
    },
    format: function (dateStr) { //天以内转换、去除秒
        let date = this.parse(dateStr)
        let diff = Date.now() - date.getTime();
        if (diff < this.UNITS['天']) {
            return this.humanize(diff);
        }
        let _format = function (number) {
            return (number < 10 ? ('0' + number) : number);
        };
        return date.getFullYear() + '/' + 
            _format(date.getMonth() + 1) + '/' + 
            _format(date.getDate()) + ' ' +
            _format(date.getHours()) + ':' + 
            _format(date.getMinutes());
    }
};


module.exports = {
    router: router,
    toast: toast,
    localStorage: localStorage,
    regPhone: regPhone,
    formatTime: formatTime,
    formatLocation: formatLocation,
    dateUtils: dateUtils
}
